﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q.Spider.Common
{
    public static class Tools
    {

        /// <summary>
        /// 获取url参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="key">参数的key</param>
        /// <returns></returns>
        public static string? GetUrlQueryString(string url, string key)
        {
            url = url.ToLower();
            var di = ParseQueryString(url);
            if (!di.ContainsKey(key.ToLower()))
            {
                return null;
            }
            return di[key.ToLower()];
        }

        /// <summary>
        /// 提取url参数并转换成字典
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static Dictionary<string, string> ParseQueryString(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException("url");
            }
            var uri = new Uri(url);
            if (string.IsNullOrWhiteSpace(uri.Query))
            {
                return new Dictionary<string, string>();
            }
            var dic = uri.Query.Substring(1)
                    .Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(param => param.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries))
                    .GroupBy(part => part[0], part => part.Length > 1 ? part[1] : string.Empty)
                    .ToDictionary(group => group.Key, group => string.Join(",", group));
            return dic;
        }


    }
}
